//
//  BaseMoreListViewController.m
//  IOSBase
//
//  Created by chenliang on 14-8-11.
//  Copyright (c) 2014年 chenliang. All rights reserved.
//

#import "BaseMoreListViewController.h"
#import "MJRefresh.h"

//刷新
static int Refresh = 1;
//加载更多
static int More = 2;

@interface BaseMoreListViewController () <MJRefreshBaseViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    CGFloat _tableViewHeight;
}
@end

@implementation BaseMoreListViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    _isNavLeftButton = NO;
    _params = [NSMutableDictionary dictionary];
    _data = [NSMutableArray array];
    _totalSize = -1;
    _currentPage = 1;
    isFirst = YES;
    _pageSize = 10;
    _totalSizeName = @"totalPage";
    
    [[UIBarButtonItem appearance] setBackgroundImage:[UIImage new]
                                            forState:UIControlStateNormal
                                          barMetrics:UIBarMetricsDefault];
    
}

-(void)initTableView:(UITableView*)tableView method:(NSString*)method listName:(NSString*)listName{
    _method = method;
    _listName = listName;
    
    _baseTableView = tableView;
    _tableViewHeight = _baseTableView.frame.size.height;
    _baseTableView.delegate = self;
    _baseTableView.dataSource = self;
    
    // 防止block循环retain，所以用__unsafe_unretained
    __unsafe_unretained BaseMoreListViewController *vc = self;
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = _baseTableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = _baseTableView;
    
    // 进入上拉加载状态就会调用这个方法
    _footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        //NSLog(@"加载更多方法调用");
        [self loadData:More];
    };
    
    if(isFirst){
        [self loadData:Refresh];
    }
    
}


-(void)initTableViewNoRefresh:(UITableView*)tableView method:(NSString*)method listName:(NSString*)listName success:(void(^)(NSDictionary *dic))success failure:(void(^)(NSError *error))failure{
    _method = method;
    _listName = listName;
    
    _baseTableView = tableView;
    _tableViewHeight = _baseTableView.frame.size.height;
    _baseTableView.delegate = self;
    _baseTableView.dataSource = self;
    
    // 防止block循环retain，所以用__unsafe_unretained
    __unsafe_unretained BaseMoreListViewController *vc = self;
    
    NSString *url = [NSString stringWithFormat:@"%@%@",BaseURL,_method];
    NSMutableDictionary *params = _params;
    [self sendASI:url params:params success:^(NSDictionary *dic){
        int code = [[dic objectForKey:@"code"] intValue];
        NSString * message = [dic objectForKey:@"message"];
        NSArray * investList = [dic objectForKey:_listName];
        success(dic);
        if(code == SUCCESS){
            if (investList.count == 0) {
                UILabel *emptyLabel = [[UILabel alloc] init];
                emptyLabel.frame = CGRectMake(0, _baseTableView.frame.origin.y + 20, WIDTH, 30);
                emptyLabel.text = @"暂无信息";
                emptyLabel.textColor = [UIColor redColor];
                emptyLabel.textAlignment = NSTextAlignmentCenter;
                [[_baseTableView superview] addSubview:emptyLabel];
                _baseTableView.hidden = YES;
                
            }
            else{
                for (UIView *v in [_baseTableView superview].subviews)
                {
                    if ([v isKindOfClass:[UILabel class]])
                    {
                        if ([((UILabel *)v).text isEqualToString:@"暂无信息"]) {
                            [v removeFromSuperview];
                        }
                    }
                }
                _baseTableView.hidden = NO;
                
                for(int i=0;i<investList.count;i++){
                    NSDictionary * p = investList[i];
                    [_data addObject:p];
                }
                [_baseTableView reloadData];
                DLog(@"success message:%@",message);
                //                    if(!_isNavLeftButton){
                //                        [self hideNavRightButton];
                //                    }else{
                //                        self.navigationItem.leftBarButtonItem = nil;
                //                    }
                
            }
            
        }
        else{
            DLog(@"BaseList code:%d message:%@",code,message);
            
            //登陆失效或超时需清空登录状态
            if (code == -1) {
                [self reLoginRefreshList];
            }
            else
            {
                [self showMessageHUD:message];
                [_baseTableView reloadData];
            }
            
        }
    }failure:^(NSError *error) {
        failure(error);
        [self showErrorHUD:@"数据加载失败..."];
        [self setNavRightButton:@"刷新" selecter:@selector(refresh)];
    }];
    
}


-(void)refresh{
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
}

-(void)clear{
    [_data removeAllObjects];
    [_baseTableView reloadData];
}

/**自定义list处理方法*/
-(void)handleData:(NSDictionary*)dic{
    
}

-(void)loadData:(int)type {
    
    if(isFirst){
        [self showProgressHUD:@"加载中"];
    }
    
    bool isEnd = NO;
    int page = _currentPage;
    if(type == Refresh){
        page = 1;
    }else{
        //判断数据是否加载完毕
        if(_data.count == _totalSize){
            isEnd = YES;
        }
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",BaseURL,_method];
    NSMutableDictionary *params = _params;
    NSString *pageSize = [NSString stringWithFormat:@"%d",_pageSize];
    [params setObject:pageSize forKey:@"pageSize"];
    NSString *currentPage = [NSString stringWithFormat:@"%d",page];
    
    if (![_method isEqualToString:@"incomOutcomQuery.htm"]) {
        [params setObject:currentPage forKey:@"pageNumber"];
    }
    else
    {
        [params setObject:currentPage forKey:@"pageNo"];
    }
    
    [self sendASI:url params:params success:^(NSDictionary *dic) {
        
        int code = [[dic objectForKey:@"code"] intValue];
        NSString * message = [dic objectForKey:@"message"];
        NSArray * investList = [dic objectForKey:_listName];
        
        if(!isEnd){
    
            if(code == SUCCESS){
                
                if (!(type == Refresh && _data.count!= 0) && _totalSize != -1 && _totalSize < _currentPage) {
                    [self showMessageHUD:@"无更多数据加载"];
                    // 结束刷新状态
                    [_header endRefreshing];
                    [_footer endRefreshing];
                    return;
                }

                [self handleData:dic];
                _totalSize = [[dic objectForKey:_totalSizeName] intValue];
                if ([dic objectForKey:@"totalCount"] != nil && ([[dic objectForKey:@"totalCount"] intValue] == 0)) {
                    UILabel *emptyLabel = [[UILabel alloc] init];
                    emptyLabel.frame = CGRectMake(0, _baseTableView.frame.origin.y + 20, WIDTH, 30);
                    emptyLabel.text = @"暂无信息";
                    emptyLabel.textColor = [UIColor redColor];
                    emptyLabel.textAlignment = NSTextAlignmentCenter;
                    [[_baseTableView superview] addSubview:emptyLabel];
                    _baseTableView.hidden = YES;

                }
                
                if(_totalSize == 0){
                    UILabel *emptyLabel = [[UILabel alloc] init];
                    emptyLabel.frame = CGRectMake(0, _baseTableView.frame.origin.y + 20, WIDTH, 30);
                    emptyLabel.text = @"暂无信息";
                    emptyLabel.textColor = [UIColor redColor];
                    emptyLabel.textAlignment = NSTextAlignmentCenter;
                    [[_baseTableView superview] addSubview:emptyLabel];
                    _baseTableView.hidden = YES;
                }
                else{
                    for (UIView *v in [_baseTableView superview].subviews)
                    {
                        if ([v isKindOfClass:[UILabel class]])
                        {
                            if ([((UILabel *)v).text isEqualToString:@"暂无信息"]) {
                                [v removeFromSuperview];
                            }
                        }
                    }
                    _baseTableView.hidden = NO;
                }
                
                //是否刷新
                Boolean isRefresh = NO;
                if(type == Refresh && _data.count!= 0){
                    isRefresh = YES;
                }else{
                    _currentPage += 1;
                }
                
                for(int i=0;i<investList.count;i++){
                    NSDictionary * p = investList[i];
                    if(!isRefresh){
                        [_data addObject:p];
                    }
                    else{
                        _data[i] = p;
                    }
                }
                [_baseTableView reloadData];
                 DLog(@"success message:%@",message);
            }else{
                
                DLog(@"BaseList code:%d   message:%@",code,message);
                if (!(type == Refresh && _data.count!= 0) && _totalSize != -1 && _totalSize < _currentPage) {
                    // 结束刷新状态
                    [_header endRefreshing];
                    [_footer endRefreshing];
                    return;
                }
                //登陆失效或超时需清空登录状态
                if (code == -1) {
                    [self reLoginRefreshList];
                }
                else
                {
                    [self showMessageHUD:message];
                    [_baseTableView reloadData];
                }

            }
        }
        if(isFirst){
            isFirst = NO;
            [self hideProgressHUD];
        }
        
        // 结束刷新状态
        [_header endRefreshing];
        [_footer endRefreshing];
        if(!_isNavLeftButton){
         [self hideNavRightButton];
        }else{
            self.navigationItem.leftBarButtonItem = nil;
        }
       
    } failure:^(NSError *error) {
        DLog(@"error %@",error);
        if(isFirst){
            isFirst = NO;
            [self hideProgressHUD];
        }

        [self showErrorHUD:@"数据加载失败..."];
        // 结束刷新状态
        [_header endRefreshing];
        [_footer endRefreshing];
        if(!_isNavLeftButton){
             [self setNavRightButton:@"刷新" selecter:@selector(refresh)];
        }else{
            
            UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithTitle:@"刷新"
                                                                              style:UIBarButtonItemStylePlain
                                                                             target:self
                                                                             action:@selector(refresh)];
            if (![self isIOS7]) {
                [refreshButton setTitleTextAttributes:
                 @{ UITextAttributeFont: [UIFont systemFontOfSize:14],
                    UITextAttributeTextShadowOffset:[NSValue valueWithUIOffset:UIOffsetZero]} forState:UIControlStateNormal];
            }
            self.navigationItem.leftBarButtonItem = refreshButton;
            }
    }];
    
}

//自己实现登陆失效后的页面刷新
-(void)reLoginRefreshList{
    
}

#pragma mark - 刷新的代理方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _header) {
        //在这里处理刷新操作
        [self loadData:Refresh];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //重新计算TableView的高度
    CGFloat height = _tableViewHeight;
    if(_data.count ==0 ){
        height = 0;
    }
    else{
        if((_baseTableView.rowHeight * _data.count) < _tableViewHeight){
            height = (_baseTableView.rowHeight * _data.count);
        }
    }
    
    _baseTableView.frame = CGRectMake(_baseTableView.frame.origin.x, _baseTableView.frame.origin.y, _baseTableView.frame.size.width, height);
    return _data.count;
}

@end
